/////////////////////////////////////////////////////////////////////////
//
// Amuse Engine SDK - core/memory
// Copyright( c) 2013.  All Rights Reserved
//
// File:		AEDefaultMemoryConfig.cpp
// Author:		Gianluca Belardelli
// Date:		20/03/2014
//
/////////////////////////////////////////////////////////////////////////
#include <AEEngine.h>
#include "memory/AEDefaultMemoryConfig.h"

// Stack Allocator di 128K per allocazioni temporanee
AEStackAllocator g_saTempStackAllocator( 128 * 1024, "TempAlloc" );

AEDefaultMemoryConfig::AEDefaultMemoryConfig( AEMemoryAllocator *lpSystemAllocator, AEMemoryAllocator *lpHeapAllocator )
{
	m_lpSystemAllocator = lpSystemAllocator;
	m_lpHeapAllocator = lpHeapAllocator;
	//m_lpMainMemMgr = AEMemoryManager::GetInstancePtr();

	m_lpInstance = this;
}

AEDefaultMemoryConfig::~AEDefaultMemoryConfig( void )
{
}

AEMemoryManager *AEDefaultMemoryConfig::MainInit( const AEMemoryConfig::AEMemoryConfigInfo &mcInfo )
{
	m_lpMainMemMgr = AEMemoryManager::GetInstancePtr();

	if( m_lpMainMemMgr == AENULL )
	{
		m_lpMainMemMgr = new ( m_lpSystemAllocator->BlockAlloc( sizeof( AEMemoryManager ) ) ) AEMemoryManager();

		m_tdThreadData[0].m_bInUse = AETRUE;
		m_tdThreadData[0].m_lpThreadMemManager = m_lpMainMemMgr;
		m_tdThreadData[0].m_lpThreadName = (char *)m_lpSystemAllocator->BlockAlloc( 16 );
		strcpy( (char *)m_tdThreadData[0].m_lpThreadName, "MainThread" );

		if( m_lpHeapAllocator == AENULL )
		{
			AEFreeListAllocator *lpFreeList = new ( m_lpSystemAllocator->BlockAlloc( sizeof( AEFreeListAllocator ) ) ) AEFreeListAllocator( mcInfo.m_uiMemorySize );
			if( lpFreeList )
			{
				m_lpHeapAllocator = lpFreeList;
			}
		}
		
		m_lpMainMemMgr->SetHeapAllocator( m_lpHeapAllocator );

		m_lpMainMemMgr->SetTempAllocator( &g_saTempStackAllocator );

	}

	return m_lpMainMemMgr;
}

AERESULT AEDefaultMemoryConfig::MainQuit( void )
{
	if( m_lpHeapAllocator )
		m_lpSystemAllocator->BlockFree( m_lpHeapAllocator, sizeof(AEFreeListAllocator) );

	m_lpSystemAllocator->BlockFree( (void *)m_tdThreadData[0].m_lpThreadName, 16 );
	m_lpSystemAllocator->BlockFree( m_lpMainMemMgr, sizeof( AEMemoryManager ) );

	return 0;
}

void AEDefaultMemoryConfig::ThreadMemInit( AEMemoryManager &refMemMgr, const char *lpName )
{
}

void AEDefaultMemoryConfig::ThreadMemQuit( AEMemoryManager &refMemMgr )
{
}
